(function($) {
	var wantArr = [];
	var pageIndex = 1;
	var oneNum = 20;
	var thisMonthStr = '';
	var upPullElement = null;
	var isPulling = false;
	var userpicker;
	$.init({
		swipeBack: true, //启用右滑关闭功能
	});

	$.plusReady(function() {
		$('.mui-scroll-wrapper').scroll({
			indicators: false //是否显示滚动条
		});
		var currentLoc = getLocalData('currentLoc');
		if(currentLoc) {
			groupCode = currentLoc['GroupCode'];
			groupDesc = currentLoc['GroupDesc'];
			locId = currentLoc['LocId'];
			locDesc = currentLoc['LocDesc'];
		} else {
			mui.toast('用户未登录');
			mui.openWindow('logon-shell.html', 'logon-shell');
			return;
		}
		setupBtns();
		
		var scrolls = document.querySelectorAll('.mui-slider-group .mui-scroll');
		mui.each(scrolls,function(index, pullRefreshEl){
			mui(pullRefreshEl).pullToRefresh({
				up: {
					callback: function() {
						upPullElement = this;
						getApplyList();
					}
				}
			});
		});
		mui('#slider').slider().stopped = true; //禁止左右滑动
		resetPullRefresh();
	});
	function getApplyList() {
		if(isPulling) {
			return;
		}
		isPulling = true;
		plus.nativeUI.showWaiting("正在加载",{modal:false});		
		var userID = getLocalData('pinfo').rw.toString();
		var startDate = document.getElementById('startDate');
		var currMonth = startDate.innerText
		var daysCount = getMonthMaxDay(currMonth);
		var stDateStr = currMonth+'-01';
		var endDateStr = currMonth+'-'+daysCount;
		var xmlStr = '<Request>' + locId + '^' + stDateStr + '^' + endDateStr + '^' +
			groupCode + '^' + userID + '^E^^' + pageIndex + '^' + oneNum + '</Request>';
		postHttpRequest(xmlStr, 'nurse.stop.getnurleavelist', function(result) {
			plus.nativeUI.closeWaiting();
			var dataArr = eval('(' + result + ')');
			for (var i = 0; i < dataArr.length;i++) {
				var oneDict = dataArr[i];
				wantArr.push(oneDict);
			}
			updateTableView(dataArr);
			if (upPullElement != null) {
				upPullElement.endPullUpToRefresh(dataArr.length < oneNum);
			}
			isPulling = false;
			pageIndex += 1;
		}, function(errorStr) {
			isPulling = false;
			if (upPullElement != null) {
				upPullElement.endPullUpToRefresh(false);
			}
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
		});
	}

	function updateTableView(dataArr) {
		var tableUl = document.getElementById('tableUl');
		var lis = tableUl.querySelectorAll('li');
		var oldLength = lis.length;
		for(var i = 0; i < dataArr.length; i++) {
			var oneDict = dataArr[i];
			var oneLi = document.createElement('li');
			oneLi.setAttribute('class', 'mui-table-view-cell');
			oneLi.id = 'li-' + (oldLength + i);
			tableUl.appendChild(oneLi);
			var AddDate = oneDict['AddDate'].substr(5,5);
			var AddTime = oneDict['AddTime'].substr(0,5);
			var addDate = AddDate +'&nbsp;' + AddTime;
			var flag = oneDict['Flag'];
			var stateClass = '';
			if (oneDict['Flag'] == 'A') {
				stateClass = 'passed';
			}else if (oneDict['Flag'] == 'R') {
				stateClass = 'refused';
			}
			oneLi.innerHTML = '<div class="applyTime">'+addDate+'</div>' +
				'<div class="label">排班日期：</div>' +
				'<div class="labelKey amKey">' + oneDict['ExpectDate'] + '</div><div></div>' +
				'<div class="label">排班类型：</div>' +
				'<div class="labelKey amKey">' + oneDict['ExpectType'] + '</div><div></div>' +
				'<div class="label">心愿班种：</div>' +
				'<div class="labelKey">' + oneDict['ExpectPostDesc'] + '</div><div></div>' +
				'<div class="statetip '+stateClass+'">' + oneDict['FlagDesc'] + '</div>';
			oneLi.addEventListener('tap', openApplyDetailPage, false);
		}
	}
	function setupBtns() {
		var today = getTodayStr();
		thisMonthStr = today.substring(0,today.length - 3);
		var startDate = document.getElementById('startDate');
		startDate.innerText = thisMonthStr;
		if (plus.os.name == 'iOS') {
			userpicker = new mui.xhPicker(2,'请选择月份','pickerId');
			var dateArr = []
			var monArr = []
			for (var i = 0; i < 12; i++) {
				var text = (i+1)
				if (text < 10) {
					text = '0'+text
				}
				monArr[i] = {'text':text}
			}
			var yearInt = new Date().getFullYear()-5;
			for (var i = 0; i < 11; i++) {
				dateArr[i] = {'text':yearInt+i,'children':monArr}
			}
			userpicker.setData(dateArr);
			startDate.addEventListener('tap', iOSSelectAbsentMonth, false);
		}else{
			startDate.addEventListener('tap', selectAbsentMonth, false);
		}
		var thisMonth = document.getElementById('thisMonth');
		thisMonth.addEventListener('tap', function() {
			var startDate = document.getElementById('startDate');
			startDate.innerText = thisMonthStr;
			resetPullRefresh();
		}, false);
		var lastMonth = document.getElementById('lastMonth');
		lastMonth.addEventListener('tap',function(){
			var startDate = document.getElementById('startDate');
			startDate.innerText = getFullLastMonth(startDate.innerText);
			resetPullRefresh();
		});
		var nextMonth = document.getElementById('nextMonth');
		nextMonth.addEventListener('tap',function(){
			var startDate = document.getElementById('startDate');
			startDate.innerText = getFullNextMonth(startDate.innerText);
			resetPullRefresh();
		});
		var wantBtn = document.getElementById('want');
		wantBtn.addEventListener('tap', function(e) {
			plus.storage.removeItem('detail');
			mui.openWindow({
				url: "wantSchEdit.html",
				id: "wantSchEdit",
				extras: {
					type: "我的心愿班"
				}
			});
			var wantSchEdit = plus.webview.getWebviewById('wantSchEdit');
			if (wantSchEdit) {
				wantSchEdit.addEventListener('close',function(){
					var detail = plus.storage.getItem('detail');
					if (detail == '1') {
						resetPullRefresh();
					}
				});
			}
		});
	}

	function selectAbsentMonth() {
		var _self = this;
		if(_self.picker) {
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				_self.picker.dispose();
				_self.picker = null;
				resetPullRefresh();
			});
		} else {
			var optionsJson = '{"type":"month"}';
			var options = JSON.parse(optionsJson);
			_self.picker = new mui.DtPicker(options);
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				_self.picker.dispose();
				_self.picker = null;
				resetPullRefresh();
			});
		}
	}
	function iOSSelectAbsentMonth(){
		var btnDom = this
		userpicker.show(function(items) {
			btnDom.innerText = items[0]['text']+'-'+items[1]['text'];
			resetPullRefresh();
		});
	}
	function resetPullRefresh(){
		var tableUl = document.getElementById('tableUl');
		tableUl.innerHTML = '';
		pageIndex = 1;
		wantArr.splice(0,wantArr.length);
		mui('#pullrefresh').scroll().scrollTo(0,0,100);
		if (upPullElement) {
			upPullElement.refresh(true);
		}
		getApplyList();
	}
	
	function openApplyDetailPage(e) {
		var id = this.id;
		var index = parseInt(id.substring(3, id.length));
		var oneDict = wantArr[index];
		if (oneDict == null) {
			return;
		}
		plus.storage.removeItem('detail');
		mui.openWindow({
			url: "applyDetail.html",
			id: "applyDetail",
			extras: {
				type: 'E',
				sourceData: oneDict
			}
		});
		var applyDetail = plus.webview.getWebviewById('applyDetail');
		if (applyDetail) {
			applyDetail.addEventListener('close',function(){
				var detail = plus.storage.getItem('detail');
				if (detail == '1') {
					resetPullRefresh();
				}
			});
		}
	}
	/*
	 * {'rw':'7','DepId':'85','DepDesc':'QKYXKPTNKBF-全科医学科(普通内科)病房','PerId':'1020','PerName':'赵霞','ExpectDate':'2020-01-16','ExpectPostId':'543','ExpectPostDesc':'节24h','ExpectType':'值班','LeaveExplain':'111111','Flag':'A','FlagDesc':'通过','AddDate':'2020-01-16','AddTime':'16:15:48','ApprovalPerName':'赵霞','ApprovalDate':'2020-01-17','ApprovalTime':'14:04:26','ApprovalExplain':''}

	 */
})(mui);
